package com.evan.review.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.evan.review.R;
import java.util.ArrayList;
import java.util.List;

/**
 * 接收方Fragment
 * 用于演示各种接收消息的方式
 */
public class ReceiverFragment extends Fragment {

    private static final String TAG = "ReceiverFragment";
    private static final String ARG_MESSAGE = "message";
    
    private TextView tvReceiverLog;
    private SharedViewModel viewModel;
    private BroadcastReceiver messageReceiver;
    private LocalBroadcastManager broadcastManager;
    // 存储早期日志消息的列表
    private List<String> pendingLogs = new ArrayList<>();
    
    /**
     * 创建带有参数的ReceiverFragment实例
     */
    public static ReceiverFragment newInstance(String message) {
        ReceiverFragment fragment = new ReceiverFragment();
        Bundle args = new Bundle();
        args.putString(ARG_MESSAGE, message);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 检查是否有通过Bundle传入的消息
        if (getArguments() != null && getArguments().containsKey(ARG_MESSAGE)) {
            String message = getArguments().getString(ARG_MESSAGE);
            // 因为此时视图还未创建，先保存消息，等视图创建后再显示
            mInitialMessage = message;
        }
        
        // 注册广播接收器
        broadcastManager = LocalBroadcastManager.getInstance(requireContext());
        registerBroadcastReceiver();
    }
    
    // 初始消息
    private String mInitialMessage;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_receiver, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvReceiverLog = view.findViewById(R.id.tv_receiver_log);
        
        // 显示所有待处理的日志消息
        if (!pendingLogs.isEmpty()) {
            for (String log : pendingLogs) {
                appendLogToTextView(log);
            }
            pendingLogs.clear();
        }
        
        // 获取ViewModel
        viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        logToUi("获取到共享ViewModel");
        
        // 监听ViewModel中的数据变化
        viewModel.getMessage().observe(getViewLifecycleOwner(), message -> {
            logToUi("ReceiverFragment通过ViewModel接收到消息: " + message);
        });
        
        // 显示初始消息，如果有的话
        if (mInitialMessage != null) {
            logToUi("通过Bundle接收到消息: " + mInitialMessage);
            mInitialMessage = null;
        }
    }
    
    /**
     * 直接接收消息
     */
    public void receiveMessage(String message) {
        logToUi("直接接收到消息: " + message);
    }
    
    /**
     * 通过ViewModel接收消息
     */
    private void receiveViaViewModel(String message) {
        logToUi("通过ViewModel接收到消息: " + message);
    }
    
    /**
     * 注册广播接收器
     */
    private void registerBroadcastReceiver() {
        messageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (SenderFragment.ACTION_SEND_MESSAGE.equals(intent.getAction())) {
                    String message = intent.getStringExtra(SenderFragment.EXTRA_MESSAGE);
                    if (message != null && isAdded()) {
                        logToUi("通过广播接收到消息: " + message);
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter(SenderFragment.ACTION_SEND_MESSAGE);
        broadcastManager.registerReceiver(messageReceiver, filter);
    }
    
    /**
     * 记录日志到UI
     */
    private void logToUi(String message) {
        if (tvReceiverLog != null) {
            appendLogToTextView(message);
        } else {
            // 视图还未创建，将日志消息添加到待处理列表
            pendingLogs.add(message);
        }
    }
    
    /**
     * 将日志添加到TextView
     */
    private void appendLogToTextView(String message) {
        String currentLog = tvReceiverLog.getText().toString();
        tvReceiverLog.setText((currentLog.isEmpty() ? "" : currentLog + "\n") + message);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        if (messageReceiver != null) {
            broadcastManager.unregisterReceiver(messageReceiver);
        }
    }
} 